// ignore_for_file: prefer_typing_uninitialized_variables, must_be_immutable

import 'package:aitao_flutter/model/gift_list_model.dart';
import 'package:aitao_flutter/request/api.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/utils/log_utils.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dots_indicator/dots_indicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../const/common_const.dart';
import '../request/requestManager.dart';
import '../style/text_style.dart';

class ShowGiftSheetWidget extends StatefulWidget {
  ShowGiftSheetWidget(
      {super.key,
      required this.rechargeCallBack,
      required this.sendGiftCallBack});
  VoidCallback rechargeCallBack;
  var sendGiftCallBack;
  @override
  State<ShowGiftSheetWidget> createState() => _ShowGiftSheetState();
}

class _ShowGiftSheetState extends State<ShowGiftSheetWidget>
    with SingleTickerProviderStateMixin {
  final List<String> _tabList = ['热门', '普通'];
  int _tabIndex = 0;
  late TabController tabController;
  List<GiftItem> hotList = [];
  List<GiftItem> normalList = [];
  int _giftIndex = -1;
  int coin = 0; // 余额
  final PageController _pageController = PageController();
  int _giftPage = 0;

  @override
  void initState() {
    super.initState();
    tabController =
        TabController(length: _tabList.length, vsync: this, initialIndex: 0);
    getGiftConfig();
  }

  void getGiftConfig() async {
    var result = await RequestManager().post(API.configGiftList);
    debugPrint('获取礼物配置');
    if (result != null && result['code'] == 0) {
      WJLogUtils.wjLog(result);
      List tempHostList = result['data']['hot_list'];
      setState(() {
        hotList = tempHostList.map((e) {
          return GiftItem.fromJson(e);
        }).toList();
        List tempNormalList = result['data']['normal_list'];
        normalList = tempNormalList.map((e) {
          return GiftItem.fromJson(e);
        }).toList();
        coin = result['data']['coin'];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
        child: Container(
      decoration: BoxDecoration(
        color: ColorStyle.whiteColor,
        borderRadius: RadiusStyle.setPortionRadius(
            PortionRaduisType.radiusTopLeftAndTopRight, 16),
      ),
      height: 420,
      child: Column(children: [
        Container(
          color: ColorStyle.whiteColor,
          padding: const EdgeInsets.fromLTRB(14, 14, 14, 10),
          child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
            Expanded(
                child: Container(
              color: ColorStyle.whiteColor,
              alignment: Alignment.center,
              child: TabBar(
                isScrollable: true,
                onTap: (index) {
                  setState(() {
                    _giftIndex = -1;
                    _tabIndex = index;
                  });
                },
                labelColor: ColorStyle.whiteColor,
                indicatorColor: ColorStyle.themeColor,
                indicatorSize: TabBarIndicatorSize.label,
                indicatorPadding: const EdgeInsets.only(left: 40, right: 40),
                indicatorWeight: 3,
                labelPadding: const EdgeInsets.only(bottom: 5),
                tabs: _tabList.asMap().entries.map((e) {
                  return Padding(
                      padding: const EdgeInsets.only(left: 40, right: 40),
                      child: Text(
                        e.value,
                        style: e.key == _tabIndex
                            ? Styles.normalText_16
                            : const TextStyle(
                                color: ColorStyle.normalTextColor,
                                fontSize: 15),
                      ));
                }).toList(),
                controller: tabController,
              ),
            )),
          ]),
        ),
        _tabIndex == 0
            ? Expanded(
                child: Padding(
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: Column(
                      children: [
                        Expanded(
                            child: Container(
                          color: Colors.white,
                          child: PageView.builder(
                              onPageChanged: (i) {
                                setState(() {
                                  _giftPage = i;
                                });
                              },
                              controller: _pageController,
                              itemCount: (hotList.length / 10).ceil(), // 计算总页数
                              itemBuilder: (context, pageIndex) {
                                // 计算每一页显示的数据范围
                                int startIndex = pageIndex * 10;
                                int endIndex = (pageIndex + 1) * 10;
                                endIndex = endIndex > hotList.length
                                    ? hotList.length
                                    : endIndex;
                                // 提取当前页的数据
                                List<GiftItem> pageData =
                                    hotList.sublist(startIndex, endIndex);

                                return GridView.builder(
                                  gridDelegate:
                                      const SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 5,
                                          crossAxisSpacing: 4.0,
                                          mainAxisSpacing: 4.0,
                                          childAspectRatio: 0.7),
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    int actualIndex =
                                        startIndex + index; // 计算实际的index
                                    return LayoutBuilder(
                                        builder: ((context, constraints) {
                                      // debugPrint('constraints:${constraints}');
                                      return GestureDetector(
                                        child: Container(
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  RadiusStyle.radiusAll(6),
                                              color: ColorStyle.whiteColor,
                                              border: Border.all(
                                                  width: 1,
                                                  color: _giftIndex ==
                                                          actualIndex
                                                      ? ColorStyle.themeColor
                                                      : ColorStyle.whiteColor)),
                                          child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                CachedNetworkImage(
                                                  imageUrl: SpUtil.getImageUrl(
                                                      pageData[index].img ??
                                                          ''),
                                                  width: 50,
                                                  height: 50,
                                                ),
                                                Box.vBox3,
                                                Text(
                                                  pageData[index].name ?? '',
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: Styles.normalText_12,
                                                ),
                                                Box.vBox3,
                                                Text(
                                                  '${pageData[index].price.toString()}${CommonStringConst.manCoinName}',
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: const TextStyle(
                                                      fontSize: 11,
                                                      color: ColorStyle
                                                          .color777777),
                                                ),
                                              ]),
                                        ),
                                        onTap: () {
                                          setState(() {
                                            _giftIndex = actualIndex;
                                          });
                                        },
                                      );
                                    }));
                                  },
                                  itemCount: pageData.length,
                                );
                              }),
                        )),
                        hotList.isEmpty
                            ? Container()
                            : DotsIndicator(
                                dotsCount: (hotList.length / 10).ceil(),
                                position: _giftPage,
                                decorator: const DotsDecorator(
                                  color: Colors.grey, // 未选中的颜色
                                  activeColor: ColorStyle.themeColor, // 选中的颜色
                                ),
                              ),
                      ],
                    )))
            : Expanded(
                child: Padding(
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: Column(
                      children: [
                        Expanded(
                            child: Container(
                          color: Colors.white,
                          child: PageView.builder(
                              onPageChanged: (i) {
                                setState(() {
                                  _giftPage = i;
                                });
                              },
                              controller: _pageController,
                              itemCount:
                                  (normalList.length / 10).ceil(), // 计算总页数
                              itemBuilder: (context, pageIndex) {
                                // 计算每一页显示的数据范围
                                int startIndex = pageIndex * 10;
                                int endIndex = (pageIndex + 1) * 10;
                                endIndex = endIndex > normalList.length
                                    ? normalList.length
                                    : endIndex;
                                // 提取当前页的数据
                                List<GiftItem> pageData =
                                    normalList.sublist(startIndex, endIndex);

                                return GridView.builder(
                                  gridDelegate:
                                      const SliverGridDelegateWithFixedCrossAxisCount(
                                          crossAxisCount: 5,
                                          crossAxisSpacing: 4.0,
                                          mainAxisSpacing: 4.0,
                                          childAspectRatio: 0.7),
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    int actualIndex =
                                        startIndex + index; // 计算实际的index
                                    return LayoutBuilder(
                                        builder: ((context, constraints) {
                                      // debugPrint('constraints:${constraints}');
                                      return GestureDetector(
                                        child: Container(
                                          decoration: BoxDecoration(
                                              borderRadius:
                                                  RadiusStyle.radiusAll(6),
                                              color: ColorStyle.whiteColor,
                                              border: Border.all(
                                                  width: 1,
                                                  color: _giftIndex ==
                                                          actualIndex
                                                      ? ColorStyle.themeColor
                                                      : ColorStyle.whiteColor)),
                                          child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                CachedNetworkImage(
                                                  imageUrl: SpUtil.getImageUrl(
                                                      pageData[index].img ??
                                                          ''),
                                                  width: 50,
                                                  height: 50,
                                                ),
                                                Box.vBox3,
                                                Text(
                                                  pageData[index].name ?? '',
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: Styles.normalText_12,
                                                ),
                                                Box.vBox3,
                                                Text(
                                                  '${pageData[index].price.toString()}${CommonStringConst.manCoinName}',
                                                  maxLines: 1,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: const TextStyle(
                                                      fontSize: 11,
                                                      color: ColorStyle
                                                          .color777777),
                                                ),
                                              ]),
                                        ),
                                        onTap: () {
                                          setState(() {
                                            _giftIndex = actualIndex;
                                          });
                                        },
                                      );
                                    }));
                                  },
                                  itemCount: pageData.length,
                                );
                              }),
                        )),
                        hotList.isEmpty
                            ? Container()
                            : DotsIndicator(
                                dotsCount: (hotList.length / 10).ceil(),
                                position: _giftPage,
                                decorator: const DotsDecorator(
                                  color: Colors.grey, // 未选中的颜色
                                  activeColor: ColorStyle.themeColor, // 选中的颜色
                                ),
                              ),
                      ],
                    ))),
        Container(
          padding: EdgeInsetsStyle.only(left: 10, right: 10),
          height: 50.w,
          color: ColorStyle.whiteColor,
          child: Row(
            children: [
              Box.hBox20,
              Text(
                '$coin${CommonStringConst.manCoinName}',
                style: Styles.mainText_14,
              ),
              Box.hBox10,
              GestureDetector(
                child: Text(
                  '充值',
                  style: Styles.mainText_14,
                ),
                onTap: () {
                  Navigator.pop(context);
                  widget.rechargeCallBack();
                },
              ),
              const Spacer(),
              GestureDetector(
                child: Container(
                  alignment: Alignment.center,
                  width: 90,
                  height: 40,
                  decoration: BoxDecoration(
                      borderRadius: RadiusStyle.radiusAll(20),
                      color: ColorStyle.themeColor),
                  child: Text(
                    '赠送',
                    style: Styles.whiteText_14,
                  ),
                ),
                onTap: () {
                  if (_giftIndex == -1) {
                    EasyLoading.showToast('请选择一个礼物');
                    return;
                  }
                  GiftItem? giftItem;
                  if (_tabIndex == 0) {
                    giftItem = hotList[_giftIndex];
                  } else if (_tabIndex == 1) {
                    giftItem = normalList[_giftIndex];
                  }
                  if (giftItem != null) {
                    Navigator.pop(context);
                    widget.sendGiftCallBack(giftItem);
                  }
                },
              )
            ],
          ),
        )
      ]),
    ));
  }
}
